<template>
    <view class="container">
        <!-- 固定顶部导航栏 -->
        <view class="fixed-header" :style="fixedHeaderStyle">
            <!-- 状态栏占位 -->
            <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

            <!-- 标题导航栏 -->
            <view class="title-navbar" :style="titleNavbarStyle">
                <!-- 切换按钮容器 -->
                <view class="switch-container">
                    <view v-for="(tab, index) in topTab" :key="index"
                        :class="['switch-item', { active: topTabIndex === index }]" 
                        :style="{ color: topTabIndex === index ? headerColor : '#ffffff' }"
                        @click="changeTopTab({ index })">
                        {{ tab.name }}
                    </view>
                    <!-- 滑动指示器 -->
                    <view class="switch-indicator" :style="indicatorStyle"></view>
                </view>
            </view>
        </view>

        <!-- 内容区域，添加顶部间距 -->
        <view class="content-area" :style="contentAreaStyle">
            <!-- 轮播图区域 -->
            <swiper class="banner-swiper" @change="onSwiperChange" circular autoplay>
                <swiper-item v-for="(item, index) in merchantMedia.promoteUrls" :key="index">
                    <image class="banner-img" :src="item.url" mode="aspectFill"></image>
                </swiper-item>
            </swiper>

            <!-- 机构信息卡片 -->
            <view class="org-card">
                <!-- 顶部：名称、公司 -->
                <view class="org-header" @click="goToShopDetail">
                    <image class="org-logo" :src="logo" mode="aspectFill" />
                    <view class="org-text">
                        <view class="org-name">{{ merchantItem.shopName || '店铺名称' }}
                            <text style="font-size: 24rpx;">{{ merchantItem.branchName }}</text>
                        </view>
                        <view class="org-company">{{ merchantInfo.name || '公司名称' }}</view>
                    </view>
                </view>

                <!-- 评分行 -->
                <view class="org-rating">
                    <image src="/static/systemIcon/shop-xingxing.jpg" mode="aspectFit" class="icon-star"></image>
                    <text class="rating">{{ orgInfo.rate || '暂无' }}</text>
                    <text class="rating-desc">{{ orgInfo.comments || 0 }}条 {{ orgInfo.comments || 0 }}人评价</text>
                    <text class="category">{{ orgInfo.businessType }}</text>
                </view>

                <!-- 营业状态 + 电话 -->
                <view class="org-business">
                    <view class="business-info">
                        <text class="status" :class="orgInfo.shopStatus == 1 ? 'status-open' : 'status-closed'">
                            {{ orgInfo.shopStatus == 1 ? '营业中' : '休息中' }}
                        </text>
                        <text class="time">{{ orgInfo.shopHours || '周一至周日 10:00-20:00' }}</text>
                    </view>
                    <image src="/static/systemIcon/shop-phone.jpg" mode="aspectFit" class="icon-phone2" @click="makeCall"></image>
                </view>

                <!-- 地址 + 定位 -->
                <view class="org-address">
                    <view class="address-text">
                        <text class="address">{{ orgInfo.address || '暂无地址' }}</text>
                        <text class="distance">距离 {{ orgInfo.distance || '1.2km' }}</text>
                    </view>
                    <image src="/static/systemIcon/shop-address.jpg" mode="aspectFit" class="icon-map" @click="openLocation"></image>
                </view>
            </view>
        </view>
        
        <!-- 全局TabBar -->
        <global-tab-bar />
    </view>
</template>

<script>
import { request } from '@/utils/request.js';
import GlobalTabBar from '@/components/GlobalTabBar.vue';

export default {
    components: {
        GlobalTabBar
    },
    data() {
        return {
            // 使用缓存的导航栏高度
            statusBarHeight: 0,
            navbarTotalHeight: 0,
            navbarHeight: 0,

            topTab: [
                { name: '货架' },
                { name: '橱窗' }
            ],
            topTabIndex: 1,
            currentTab: 0, // 底部标签栏当前选中项
            currentBanner: 0, // 当前轮播图索引
            // 头部颜色相关
            headerColor: '#39B54A', // 默认绿色
            businessType: 1, // 默认业务类型
            // 机构信息
            orgInfo: {
                name: '', // 机构名称
                logo: '', // 机构logo
                shopImages: [
                    {
                        url: 'https://big-event-kda.oss-cn-beijing.aliyuncs.com/wjj/l2.jpg'
                    },
                    {
                        url: 'https://big-event-kda.oss-cn-beijing.aliyuncs.com/wjj/q1.jpg'
                    },
                    {
                        url: 'https://big-event-kda.oss-cn-beijing.aliyuncs.com/wjj/l3.jpg'
                    },
                ], // 轮播图
                branchName: '', // 分店名称
                shopHours: '',  // 营业时间 周一至周五 09:00-18:00
                businessName: '', // 公司名称
                businessType: 0, // 经营类型 1-景区 2-旅行社 3-教培
                shopStatus: 0,  // 店铺状态 0-关闭 1-营业中
                address: '',    // 地址
                count: 0, // 轮播图数量
                rate: 4.8, // 评分
                comments: 128, // 评价数量
                distance: '1.2km', // 距离
            },
            merchantItem: {},
            merchantMedia: {},
            logo: '',
            // 商家基本信息（从本地存储获取）
            merchantInfo: null,
            // 加载状态
            loading: true
        };
    },
    async onLoad() {
        // 获取缓存的导航栏高度
        this.initNavbarHeight();
        // 获取商家类型和颜色
        this.getBusinessType();
        await this.fetchShopInfo();
        await this.getMerchantItem();
        await this.getMerchantMedia();
    },
    computed: {
        // 固定头部样式
        fixedHeaderStyle() {
            return {
                position: 'fixed',
                top: 0,
                left: 0,
                right: 0,
                zIndex: 999,
                backgroundColor: '#ffffff',
                boxShadow: '0 2rpx 8rpx rgba(0, 0, 0, 0.1)'
            }
        },

        // 标题导航栏样式
        titleNavbarStyle() {
            return {
                height: this.navbarHeight + 'px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                backgroundColor: '#ffffff'
            }
        },

        // 内容区域样式
        contentAreaStyle() {
            return {
                paddingTop: this.navbarTotalHeight + 'px'
            }
        },

        // 滑动指示器样式
        indicatorStyle() {
            const itemWidth = 100 / this.topTab.length // 每个按钮的宽度百分比
            return {
                left: (this.topTabIndex * itemWidth) + '%',
                width: `calc(${itemWidth}% - 8rpx)`,
                marginLeft: '4rpx'
            }
        }
    },
    methods: {
        // 获取商家类型和颜色
        getBusinessType() {
            try {
                const companyInfo = uni.getStorageSync('companyInfo');
                if (companyInfo && companyInfo.businessType !== undefined && companyInfo.businessType !== null) {
                    this.businessType = companyInfo.businessType;
                    console.log('店铺页面 - businessType:', this.businessType);

                    switch (this.businessType) {
                        case 1:
                            this.headerColor = '#0081ff'; // 蓝色
                            console.log('店铺页面 - 设置为蓝色');
                            break;
                        case 2:
                            this.headerColor = '#39B54A'; // 绿色
                            console.log('店铺页面 - 设置为绿色');
                            break;
                        case 3:
                            this.headerColor = '#FBBD08'; // 黄色
                            console.log('店铺页面 - 设置为黄色');
                            break;
                        default:
                            this.headerColor = '#39B54A'; // 默认绿色
                            console.log('店铺页面 - 设置为默认绿色');
                            break;
                    }
                    console.log('店铺页面 - 最终头部颜色:', this.headerColor);
                } else {
                    console.log('店铺页面 - companyInfo或businessType不存在，使用默认颜色');
                    this.headerColor = '#39B54A'; // 默认绿色
                }
            } catch (error) {
                console.error('店铺页面 - 读取companyInfo失败:', error);
                this.headerColor = '#39B54A'; // 默认绿色
            }
        },
        
        // 初始化导航栏高度
        initNavbarHeight() {
            // 使用全局注册的navbarUtil方法
            this.statusBarHeight = this.$navbarUtil.getStatusBarHeight()
            this.navbarHeight = this.$navbarUtil.getNavbarHeight()
            this.navbarTotalHeight = this.$navbarUtil.getNavbarTotalHeight()

            console.log('店铺页面 - 导航栏高度:', {
                statusBarHeight: this.statusBarHeight,
                navbarHeight: this.navbarHeight,
                navbarTotalHeight: this.navbarTotalHeight
            })
        },
        //获取商户基本信息
        async getMerchantItem() {
            const res = await request({
                url: `/merchant-item/getByMerchantId?merchantId=${this.merchantInfo.id}`,
                method: 'GET',
                loading: true
            });
            this.merchantItem = res.data || {};
            console.log('商户基本信息', this.merchantItem);
        },
        //获取商家媒体信息
        async getMerchantMedia() {
            const res = await request({
                url: `/merchantMedia/${this.merchantInfo.id}`,
                method: 'GET',
                loading: true
            });
            this.merchantMedia = res.data || {};
            console.log('商户媒体信息', this.merchantMedia);
            this.logo = this.merchantMedia.logoUrls[0].url || this.merchantMedia.logoUrls[1].url
            console.log('商户logo', this.logo);
        },


        goToShopDetail() {
            uni.navigateTo({ url: `/public/merchant/shopDetail/index` });
        },
        onSwiperChange(e) {
            this.currentBanner = e.detail.current;
        },
        changeTopTab(e) {
            this.topTabIndex = e.index;
            if (e.index === 0) {
                // 首页
                uni.redirectTo({ url: '/pages/merchant/index/index' });
            }
            // 当前已是店铺页面，无需跳转
        },

        // 切换底部标签栏
        switchTab(index) {
            this.currentTab = index;
            // 可以根据不同的tab索引加载不同内容或跳转到不同页面
            switch (index) {
                case 0:
                    // 商品/服务
                    console.log('切换到商品/服务');
                    break;
                case 1:
                    // 指导团队
                    console.log('切换到指导团队');
                    break;
                case 2:
                    // 更多服务
                    console.log('切换到更多服务');
                    break;
                case 3:
                    // 用户评价
                    console.log('切换到用户评价');
                    break;
            }
        },

        // 获取商家信息
        async fetchShopInfo() {
            this.loading = true;
            try {
                // 1. 从本地存储获取商家基本信息
                this.merchantInfo = await this.getCompanyInfo();
                console.log('商家信息', this.merchantInfo);
                // 3. 如果有商家信息，获取详细数据
                if (this.merchantInfo) {
                    // 先显示本地存储的基本信息
                    this.orgInfo = {
                        ...this.orgInfo,
                        logo: this.merchantInfo.logo || '',
                        name: this.merchantInfo.name,
                        businessType: this.merchantInfo.businessType,
                    };

                    // 并行获取其他详细信息，提高加载速度
                    await Promise.all([
                        // this.fetchMerchantItem(),

                    ]);
                }
            } catch (err) {
                console.error('获取商家信息失败', err);
                // 发生错误时显示友好提示
                uni.showToast({
                    title: '获取商家信息失败',
                    icon: 'none'
                });
            } finally {
                this.loading = false;
            }
        },



        // 从本地存储获取企业信息
        getCompanyInfo() {
            return new Promise((resolve) => {
                uni.getStorage({
                    key: 'companyInfo',
                    success: (res) => {
                        resolve(res.data);
                    },
                    fail: () => {
                        resolve(null);
                    }
                });
            });
        },

        // 调用商家基本信息接口
        async fetchMerchantItem() {
            try {
                const res = await request({
                    url: `/merchant-item/getByMerchantId?merchantId=${this.merchantInfo.id}`,
                    method: 'GET',
                    loading: false
                });
                console.log('商家基本信息', res.data)
                if (res.code === 200) {
                    const data = res.data || {};
                    // 更新页面显示的商家信息
                    this.orgInfo = {
                        ...this.orgInfo,
                        branchName: data.branchName,
                        shopHours: data.shopHours || '',
                        businessName: data.businessName || '',
                        address: data.address || '',
                        shopStatus: data.shopStatus,
                        shopImages: data.shopImages || [],
                    };
                    this.orgInfo.businessType = this.getbusinessType();
                    this.count = this.orgInfo.shopImages.length;
                }
            } catch (err) {
                console.error('获取商家详细信息失败', err);
            }
        },
        getbusinessType() {
            if (this.orgInfo.businessType == 1) {
                return '景区'
            } else if (this.orgInfo.businessType == 2) {
                return '旅行社'
            } else if (this.orgInfo.businessType == 3) {
                return '教培'
            } else {
                return '其他'
            }
        },
        // 拨打电话
        makeCall() {
            if (this.orgInfo.phoneNumber) {
                uni.makePhoneCall({
                    phoneNumber: this.orgInfo.phoneNumber,
                    fail: (err) => {
                        console.log('拨打电话失败', err);
                        uni.showToast({
                            title: '拨打电话失败',
                            icon: 'none'
                        });
                    }
                });
            } else {
                uni.showToast({
                    title: '暂无联系电话',
                    icon: 'none'
                });
            }
        },

        // 打开地图
        openLocation() {
            if (this.orgInfo.address) {
                // 模拟经纬度信息
                const latitude = 39.9042;
                const longitude = 116.4074;

                uni.openLocation({
                    latitude: this.orgInfo.location.latitude || latitude,
                    longitude: this.orgInfo.location.longitude || longitude,
                    name: `${this.orgInfo.shortName}${this.orgInfo.branch ? '(' + this.orgInfo.branch + ')' : ''}`,
                    address: this.orgInfo.address,
                    fail: (err) => {
                        console.log('打开地图失败', err);
                        uni.showToast({
                            title: '打开地图失败',
                            icon: 'none'
                        });
                    }
                });
            } else {
                uni.showToast({
                    title: '暂无地址信息',
                    icon: 'none'
                });
            }
        }
    },
};
</script>

<style scoped>
/* 全局样式 */
.container {
    background-color: #f8f8f8;
    min-height: 100vh;
}

/* 固定头部样式 */
.fixed-header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 999;
    background-color: #ffffff;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.status-bar {
    width: 100%;
    background-color: inherit;
}

/* 标题导航栏样式 */
.title-navbar {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #ffffff;
}

.switch-container {
    position: relative;
    display: flex;
    width: 200rpx;
    height: 60rpx;
    background-color: v-bind(headerColor);
    border-radius: 30rpx;
    overflow: hidden;
}

.switch-item {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    color: #ffffff;
    transition: all 0.3s ease;
    position: relative;
    z-index: 2;
}

.switch-item.active {
    color: v-bind(headerColor);
    font-weight: 600;
}

.switch-indicator {
    position: absolute;
    top: 6rpx;
    height: calc(100% - 10rpx);
    background-color: #ffffff;
    border-radius: 28rpx;
    transition: all 0.3s ease;
    z-index: 1;
}

/* 内容区域样式 */
.content-area {
    padding-top: 0;
    padding-bottom: 160rpx; /* 为底部tabbar留出空间 */
    /* 由computed动态设置 */
}

.org-header {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10rpx 0;
}

.org-text {
    flex: 1;
    height: 110rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.org-logo {
    width: 120rpx;
    height: 120rpx;
    border-radius: 22rpx;
    margin-right: 20rpx;
    /* 控制logo与文字之间的间距 */
}

.org-tex {
    flex: 2;
}

.tab-container {
    width: 33%;
    display: flex;
    justify-content: center;
    padding: 20rpx;
    border-radius: 20rpx;
}

.banner-img {
    width: 100%;
    height: 100%;
}

.banner-swiper {
    width: 100%;
    height: 500rpx;
    position: relative;
    background-color: #f0f0f0;
}

.image-count {
    position: absolute;
    bottom: 70rpx;
    left: 50%;
    transform: translateX(-50%);
    background-color: rgba(0, 0, 0, 0.5);
    color: #fff;
    padding: 6rpx 20rpx;
    border-radius: 20rpx;
    font-size: 26rpx;
    z-index: 10;
}


/* 机构卡片 */
.org-card {
    position: absolute;
    top: 600rpx;
    left: 20rpx;
    right: 20rpx;
    padding: 30rpx;
    background-color: #fff;
    border-radius: 20rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
}

/* 名称 */
.org-name {
    font-size: 32rpx;
    color: #333333;
    margin-bottom: 6rpx;
}

.org-company {
    font-size: 24rpx;
    color: #999999;
}

/* 评分区域 */
.org-rating {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
}

.rating {
    font-size: 32rpx;
    color: #FC642F;
    margin: 0 20rpx 0 0;
}

.rating-desc {
    flex: 1;
    font-size: 24rpx;
    color: #333333;
}

.category {
    background-color: #f0f9ff;
    color: #1989fa;
    font-size: 26rpx;
    padding: 6rpx 16rpx;
    border-radius: 16rpx;
}

/* 营业状态 */
.org-business {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
}

.business-info {
    flex: 1;
    min-width: 0;
    display: flex;
    align-items: center;
}

.status {
    font-size: 28rpx;
    padding: 6rpx 16rpx;
    border-radius: 12rpx;
    margin-right: 20rpx;
}

.status-open {
    color: #00cc66;
    background-color: #e8f9f1;
}

.status-closed {
    color: #909399;
    background-color: #f5f5f5;
}

.time {
    font-size: 24rpx;
    color: #333333;
}

/* 地址行 */
.org-address {
    display: flex;
    align-items: center;
    margin-top: 20rpx;
}

.address-text {
    flex: 1;
    color: #333333;
    font-size: 24rpx;
}

.address {
    font-size: 24rpx;
    color: #333333;
    line-height: 48rpx;
    display: block;
}

.distance {
    font-size: 24rpx;
    color: #333333;
}


/* 图标样式 */
.icon-arrow {
    transition: transform 0.3s;
}

.icon-arrow:active {
    transform: scale(0.9);
}

.icon-star {
    width: 34rpx;
    height: 34rpx;
    margin-right: 8rpx;
}

.icon-phone,
.icon-map {
    width: 48rpx;
    height: 48rpx;
    transition: all 0.3s;
    flex-shrink: 0;
    box-sizing: border-box;
}
.icon-phone2{
    width: 48rpx;
    height: 48rpx;
}

/* 服务区域 */
.services-section {
    margin: 20rpx;
    padding: 30rpx;
    background-color: #fff;
    border-radius: 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    margin-bottom: 30rpx;
}

.section-title {
    font-size: 36rpx;
    font-weight: bold;
    margin-bottom: 30rpx;
    color: #303133;
}

.services-grid {
    display: flex;
    justify-content: space-between;
}

.service-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 20%;
}

.service-item .service-text {
    font-size: 26rpx;
    color: #606266;
    margin-top: 16rpx;
}

/* 推荐区域 */
.recommend-section {
    margin: 20rpx;
    margin-bottom: 140rpx;
}

.recommend-list {
    display: flex;
    justify-content: space-between;
}

.recommend-item {
    width: 48%;
    background-color: #fff;
    border-radius: 20rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.recommend-img {
    width: 100%;
    height: 240rpx;
}

.recommend-info {
    padding: 20rpx;
}

.recommend-title {
    font-size: 28rpx;
    color: #303133;
    margin-bottom: 10rpx;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.recommend-price {
    font-size: 32rpx;
    color: #f56c6c;
    font-weight: bold;
}

.price-unit {
    font-size: 24rpx;
    color: #f56c6c;
    font-weight: normal;
}

/* 底部标签栏 */
.tab-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    display: flex;
    justify-content: space-around;
    padding: 10rpx 0 20rpx 0;
    background-color: #fff;
    border-top: 1rpx solid #eee;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.tab-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 10rpx 0;
    transition: all 0.3s;
}

.tab-item:active {
    opacity: 0.7;
}

.tab-item text {
    font-size: 24rpx;
    color: #909399;
    margin-top: 8rpx;
}

.tab-active text {
    color: #1989fa;
}
</style>
